import React, {useEffect, useRef, useState} from 'react';
import {View, StyleSheet, Button, Text, ScrollView, Image, Platform, PermissionsAndroid, Alert} from 'react-native';
import {ThemeColor} from '../utils/common';
import TouchableView from '../components/touchableView';
import screen from '../utils/screen';
import Images from '../images/Images';
import {useHeaderHeight} from '@react-navigation/elements';
import {useNavigation, useRoute} from '@react-navigation/native';
import LGBtn from '../components/touchableView/lgBtn';
import {useAppStore} from '../store/useAppStore';
import {readNativeFile, openAssignFolder, writeByteToFile,decodeNativeFile} from '../utils/nativeUtil';
import {formatTimestamp} from '../utils/dateUtil';
const RNFS = require('react-native-fs');
const FileOpener = require('react-native-file-opener3');
import RNFetchBlob, {RNFetchBlobFetchPolyfill} from 'rn-fetch-blob';

import {DownloadDirectoryPath} from 'react-native-fs';
import {useToast} from '../components/toast/useToast';
import {useLoading} from '../components/loading/useLoading';
import {readString} from 'react-native-csv';

const mime = require('react-native-mime-types')

// const fileName = 'demoAPP_content.csv'
// const SavePath = Platform.OS === 'ios' ? RNFS.DocumentDirectoryPath : RNFS.ExternalDirectoryPath;
// const sampleDocFilePath =  SavePath + '/' + fileName;

const saveDir = RNFS.DownloadDirectoryPath + '/EthShare'

const Result = ()=>{

    const [data,setData] = useState(null)
    const headerHeight = useHeaderHeight()
    const navigation = useNavigation()
    const toast = useToast()
    const loading = useLoading()
    const {params} = useRoute()
    const {appState:{ethShare,authHash},updateAppState} = useAppStore()
    const downloadPath = useRef(null)
    const [decodeFile,setDecodeFile] = useState(null)

    useEffect(()=>{


        navigation.setOptions({
            headerTitle:params.title
        })

        if(params.showAuth){
            const hash = '0x' +  '0029039301fe9010e0e176d20a08b9255039a24da521683475cdd99c8ae72a0a'
            let req1 = ethShare.getVaultDetail(hash)
            let req2 = ethShare.getVaultItem(hash)
            Promise.all([req1,req2]).then(results=>{
                let detail = {}
                results.forEach(res=>{
                    const json = res.output.result[0]
                    detail = {...detail,... JSON.parse(json) }
                })
                console.log('detail:',detail);
                setData(detail)

                const savePath = saveDir + '/' + detail.file_name;
                RNFS.exists(savePath).then(exist=> {
                    if (exist) {
                        console.log('saved:', savePath);
                        setDecodeFile(savePath)
                    }
                })
            }).catch(error=>{
                console.log('失败：',error);
            })

        }

        RNFS.exists(saveDir).then(isExits=>{
            console.log('dir exist:',isExits);
            if(isExits){

            }else{
                RNFS.mkdir(saveDir).then(()=>{
                    console.log('dir maked:',saveDir );
                })
            }
        })

    },[])


    useEffect(()=>{
        console.log('decodeFile effect');
        if(decodeFile){
            navigation.setOptions({
                headerRight: ()=>{
                    return (
                        <TouchableView
                            style={{width:30,height:30,justifyContent:'center',alignItems:'center'}}
                            onPress={()=>onDeletePress(decodeFile)}
                        >
                            <Image source={Images.delete}
                                   style={{width:20,height:20,tintColor:'#333'}}
                                   resizeMode={'contain'}/>
                        </TouchableView>
                    )
                }
            })
        }else{
            navigation.setOptions({
                headerRight:null
            })
        }

    },[decodeFile])

    const onDeletePress = (path)=>{
        Alert.alert('提示','删除所选内容？',
            [
                {text:'确定',onPress:()=>{
                        RNFS.unlink(path).then(()=>{
                            console.log('delete',path);
                            setDecodeFile(null)

                        })
                    },style:'default'},
                {text:'取消',onPress:()=>{},style:'default'}
            ]
        )
    }

    const downloadFile = (downloadUrl,path)=>{
        loading.show('下载中');

        RNFetchBlob.config({
            fileCache:true,
            path:path
        }).fetch('GET',downloadUrl).progress((received, total) => {
            console.log("download progress", received / total);
        }).then(resp=>{
            loading.hide()
        }).catch(error=>{

        })
        /* const task = RNFS.downloadFile({
             fromUrl:downloadUrl,
             toFile:downloadFile,
             background:true,
             begin:res => {
                 console.log('begin :',res);
             },
             progress:res => {
                 console.log('progress:',res);
             }
         })
         task.promise.then(res=>{
             console.log('download done:',res);
         }).catch(err=>{
             console.log('err',err);
         })
*/

    }

    const readFile = (paths,pwd,fileName)=> {

        const savePath = saveDir + '/' + fileName;
        RNFS.exists(savePath).then(exist=>{
            if(exist){
                console.log('saved:',savePath);
                openFile()
            }else{
                console.log('start decode');

                const key = ethShare.decryptPassword(pwd)
                console.log('---',key);
                console.log('---',key.length);

                decodeNativeFile(paths,savePath,key).then(res=>{
                    console.log('decode:',res);
                    setDecodeFile(savePath)
                    console.log();
                }).catch(error=>{
                    console.log(error);
                })



            }
        })



    }


    const openFile = ()=>{
        console.log('path:',decodeFile);

        const key = 'android.permission.READ_EXTERNAL_STORAGE'
        PermissionsAndroid.check(key).then(grant=>{
            console.log('permission :',grant);
            if(!grant){
                PermissionsAndroid.request(key).then(status=>{
                    console.log(status);
                })
            }else{
                // navigation.navigate('FSDemo',{path:decodeFile})
                /*
                FileOpener.open(
                    decodeFile,
                    'application/msword'
                ).then(()=>{
                    console.log('success!!');
                },(e)=>{
                    console.log('error!!');
                })
                */
                readNativeFile(decodeFile).then(content=>{
                    console.log(content);
                    const results = readString(content.trim());
                    console.log('csv test:',results);
                    navigation.navigate('Table',{data:results.data,title:params.title})
                })

            }
        })


       /* RNFS.exists(downloadPath.current).then(exist=>{
            if(exist){

            }else{
                //从assets拷贝到目标目录
                RNFS.copyFileAssets(fileName,sampleDocFilePath).then(()=>{
                    console.log('copy success');
                }).catch(error=>{
                    console.log('copy error');
                })
            }
            console.log('exist:',exist);
        })
*/
    }

    const onOpenFile = async ()=>{

        if(!data) return

        if(decodeFile){
            openFile()
            return
        }

        const {file_name,file_hash,pwd} = data
        const downloadFilePath = RNFS.DocumentDirectoryPath + `/${file_hash}.vault`;
        const{account} = ethShare
        let downloadUrl = `http://172.30.5.21:7070/witness/witnessTask/downloadWitnessFile?account=${account.address}&hash=${authHash}`
        console.log('downloadUrl:',downloadUrl);

        RNFS.exists(downloadFilePath).then(isExist=>{
            if(isExist){
                readFile(downloadFilePath,pwd,file_name)
                console.log('文件已下载:',downloadFilePath);
            }else{

                downloadFile(downloadUrl,downloadFilePath)
            }
        })
    }

    return (
        <View style={[styles.container,{paddingTop:headerHeight}]}>

            <ScrollView
                contentContainerStyle={{paddingTop:30,paddingHorizontal:20}}
            >
                <Text style={styles.title}>文件名称:</Text>
                <Text style={styles.value}>{data && data.file_name}</Text>
                <View style={styles.line}/>

                <Text style={styles.title}>提交时间：</Text>
                <Text style={styles.value}>{data && formatTimestamp(data.create_time,'yyyy-MM-dd')}</Text>
                <View style={styles.line}/>

                <Text style={styles.title}>Hash：</Text>
                <Text style={styles.value}>{data && data.file_hash}</Text>

                <LGBtn
                    title={'查看明文'}
                    style={styles.nextBtn}
                    onPress={onOpenFile}
                />

            </ScrollView>


        </View>
    )
}

export default Result

const styles = StyleSheet.create({
    container:{
        flex:1, backgroundColor:ThemeColor.theme
    },
    title:{
        color:'#666',fontSize:15
    },
    value:{
        color:'#333',fontSize:16,fontWeight:'500'
    },
    line:{
        height:0.3,backgroundColor: '#eee',width:'100%',marginVertical: 10
    },
    nextBtn:{
        alignSelf:'center',marginVertical:30
    }
})
